package com.fluagen.example.vertx.templates;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class MD5Util {

	public static String getMD5(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException{
		MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] messageDigest = md.digest(input.getBytes("UTF-8"));
        BigInteger number = new BigInteger(1, messageDigest);
        String hashtext = number.toString(16);
        while (hashtext.length() < 32) {
            hashtext = "0" + hashtext;
        }
        return hashtext.toLowerCase();
    }
	
	public static String md5(Map<String, String> params, String secret){
		StringBuilder raw = new StringBuilder(secret);
		params.entrySet().stream().sorted(Map.Entry.<String,String>comparingByKey()).forEachOrdered(e -> {
			raw.append(e.getKey()).append(e.getValue());
		});
		raw.append(secret);
		String sign = "";
		try {
			sign = MD5Util.getMD5(raw.toString());
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		return sign;
	}
	
	public static void main(String[] args){
		
		String timestamp = System.currentTimeMillis()+"";
		String secret = "secret.api.a000001.las.001";
		
		Map<String,String> params = new HashMap<String,String>();
		
		params.put("client_id", "api.a000001.las.001");
		params.put("tenant_id", "testlib");
		params.put("timestamp", timestamp);
		params.put("access_token", "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ6aGFuZ3NhbiIsInVzZXJfaWQiOiI3MjYxZWNhYWUzYTc0ZGM2OGI0NjhlMTJhNzBiMWFlYyIsInRlbmFudCI6InRlc3RsaWIifQ.ofVPznYs8ioS7K6gc8TMCIOw5YCk1WuKkcWyMXXTJxRxRq826I4kYfXVTIBG3H9HyPI7nVQ60vx5AFCfvXEXDA");
		
		String sign = md5(params,secret);
		
		System.out.println("timestamp:"+timestamp);
		System.out.println("sign:"+sign);
		
	}
}
